package biznussoft.fieldservice360.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import biznussoft.fieldservice360.HomeActivity;
import biznussoft.fieldservice360.R;
import biznussoft.fieldservice360.lookup.ItemLookup;
import biznussoft.fieldservice360.lookup.SitesLookup;
import biznussoft.fieldservice360.model.Bean_Class;
import biznussoft.fieldservice360.model.ItemModel;
import biznussoft.fieldservice360.model.SiteInventoryModel;
import biznussoft.fieldservice360.model.SiteModel;
import biznussoft.fieldservice360.utils.Session;

import com.example.zbarcodelibrary.ZBarConstants;
import com.example.zbarcodelibrary.ZBarScannerActivity;
import com.google.gson.Gson;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class InventoryFragment extends BaseFragment implements OnClickListener {
	private static final int ZBAR_SCANNER_REQUEST = 0;
	private static final int ZBAR_QR_SCANNER_REQUEST = 1;
	private String barcode;
	private EditText etSerialid;
	public static EditText etItemId,etQuantity,etSite;
	public static TextView tvQuatitiy,commonText;
	public static RelativeLayout idLayout;
	private Button createInventory;
	private String itemId,siteId;
	private TextView ItemID,Discription,SerialId,lotId,Quantity,Name,Price; 
	private LinearLayout newInventoryLayout,llInventoryDetail;
	public static ArrayList<ItemModel> itemIdlist;
	public static ArrayList<SiteModel> siteList;
	boolean isFiltered;
	private RestClient client;  
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.inventory_fragment, null);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);

	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);

		MenuItem actionItem = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(actionItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		actionItem.setIcon(R.drawable.logout); 

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if(item.getTitle().equals("Logout")){
			SalesforceSDKManager.getInstance().logout(getActivity());}
		return super.onOptionsItemSelected(item);
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		idLayout = (RelativeLayout) getView().findViewById(R.id.rrlayoutId);
		etItemId = (EditText) getView().findViewById(R.id.itemid);
		etSerialid = (EditText) getView().findViewById(R.id.serialid);
		etQuantity = (EditText) getView().findViewById(R.id.quantity);
		etSite = (EditText) getView().findViewById(R.id.site);
		tvQuatitiy = (TextView) getView().findViewById(R.id.textQuantity);
		commonText = (TextView) getView().findViewById(R.id.commontext);
		createInventory = (Button) getView().findViewById(R.id.createInventory);
		etSite.setOnClickListener(this);
		createInventory.setOnClickListener(this);
		etSerialid.setOnClickListener(this);
		ItemID = (TextView) getView().findViewById(R.id.itemId);
		Discription = (TextView) getView().findViewById(R.id.discription);
		SerialId = (TextView) getView().findViewById(R.id.SerialID);
		lotId = (TextView) getView().findViewById(R.id.LotID);
		Quantity = (TextView) getView().findViewById(R.id.Quantity);
		Name = (TextView) getView().findViewById(R.id.Name);
		Price = (TextView) getView().findViewById(R.id.Price);

		newInventoryLayout = (LinearLayout) getView().findViewById(R.id.llNewInventory);
		llInventoryDetail = (LinearLayout) getView().findViewById(R.id.llInventoryDetail);
		etItemId.setOnClickListener(this);
		client = HomeActivity.mActivity.client;

		retriveSiteID();
	}

	public void getInventoryDetails(int Position){
		llInventoryDetail.setVisibility(View.VISIBLE);
		SiteInventoryModel bean = WarehouseDetailsFragment.inventoryList.get(Position);
		ItemID.setText(bean.getItemId());
		Discription.setText(bean.getDescription());
		SerialId.setText(bean.getSerialId());
		lotId.setText(bean.getLotId());
		Quantity.setText(bean.getQuantitiy());
		Name.setText(bean.getName());
		Price.setText(bean.getPrice());
	}

	public void showInventory(String id){
		siteId = id;
		retriveItems();
		llInventoryDetail.setVisibility(View.GONE);
		newInventoryLayout.setVisibility(View.VISIBLE);
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.itemid:
			ItemLookup lookup = new ItemLookup();
			lookup.getItemLookUp(getActivity(),"Inventory");
			break;
		case R.id.createInventory:
			createInventory();
			break;
		case R.id.serialid:
			getBarCode();
			break;
		case R.id.site:
			SitesLookup sLookUp  = new SitesLookup();
			sLookUp.getItemLookUp(getActivity(),"Inventory");
			break;
		default:
			break;
		}

	}

	public void retriveItems(){

		try{

			String accounts = "SELECT Name,Id,FConnect__Lot_Control__c,FConnect__Serial_Control__c FROM FConnect__Item__c";
			Log.i("TPT","SOQL is     :"+accounts);
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {

						Log.i("TPT","Contact is   :"+result);

						JSONObject jsonObject1 = new JSONObject(result.asString());
						Log.i("NCS","jsonobject1  is  :"+jsonObject1.length());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");
						Log.i("RGT","jsonArray  is  :"+jsonArray.length());

						itemIdlist = new ArrayList<ItemModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								ItemModel bean = _gson.fromJson(jsonArray.getString(i), ItemModel.class);
								itemIdlist.add(bean);
							}
						}     


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);

				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}




	}



	public void createInventory(){

		String objectType = "FConnect__Inventory__c";                                 
		HashMap<String, Object> fields = new HashMap<String, Object>();
		fields.put("FConnect__Item__c", itemId);
		if (Session.sIdFlag) {
			fields.put("FConnect__Serial_ID__c", etSerialid.getText().toString());
		} else {
			fields.put("FConnect__Lot_ID__c", etSerialid.getText().toString());
		}
		fields.put("FConnect__Quantity__c", etQuantity.getText().toString());
		fields.put("FConnect__Site__c", Session.sSiteId);

		try {
			RestRequest restRequest = RestRequest.getRequestForCreate(Bean_Class.api_Version,objectType,fields);
			Log.i("NCS","REquest is  :"+restRequest);
			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {     
						Log.i("TPT","Response is   :"+result);
						JSONObject json = new JSONObject(result.toString());
						if(json!= null){
							Log.i("TPT","Response is   :"+json.getString("success"));
							if(json.getString("success").equalsIgnoreCase("true")){}
						}
					}                                
					catch (Exception e) {
						Log.i("TPT","Exception is   :"+e.getMessage());                      
					}
				}
				//@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});
		} 
		catch (Exception e) {
			Log.i("NCS","Exception is   :"+e.getMessage());
		}
	}


	public void getBarCode(){
		Intent intent = new Intent(getActivity(), ZBarScannerActivity.class);
		startActivityForResult(intent, ZBAR_SCANNER_REQUEST);
	}

	@SuppressWarnings("static-access")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch (requestCode) {
		case ZBAR_SCANNER_REQUEST:
		case ZBAR_QR_SCANNER_REQUEST:
			if (resultCode ==getActivity().RESULT_OK) {
				barcode = data.getStringExtra(ZBarConstants.SCAN_RESULT);
				Log.i("NCS","bar code is  :"+barcode);
				etSerialid.setText(barcode);
			} else if(resultCode == getActivity().RESULT_CANCELED && data != null) {
				String error = data.getStringExtra(ZBarConstants.ERROR_INFO);
				if(!TextUtils.isEmpty(error)) {
				}
			}
			break;
		}
	}

	public void retriveSiteID(){

		try{

			String accounts = "SELECT Name,Id FROM FConnect__Site__c";
			Log.i("TPT","SOQL is     :"+accounts);
			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {

						Log.i("TPT","Contact is   :"+result);

						JSONObject jsonObject1 = new JSONObject(result.asString());
						Log.i("NCS","jsonobject1  is  :"+jsonObject1.length());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");
						Log.i("RGT","jsonArray  is  :"+jsonArray.length());

						siteList = new ArrayList<SiteModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								SiteModel bean = _gson.fromJson(jsonArray.getString(i), SiteModel.class);
								siteList.add(bean);
							}
						}     


					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);

				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}




	}

}
